package com.two.screen.water.balance.utils;

import java.math.BigInteger;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

/**
 * AES加密解密工具
 *
 * @author huangxiaoguo
 */
public class AESUtils {

    /**
     * AES加密
     *
     * @param data 将要加密的内容
     * @param key  密钥
     * @return 已经加密的内容
     */
    public static byte[] encrypt(byte[] data, byte[] key) {
        //不足16字节，补齐内容为差值
        int len = 16 - data.length % 16;
        for (int i = 0; i < len; i++) {
            byte[] bytes = {(byte) len};
            data = ArrayUtils.concat(data, bytes);
        }
        try {
            SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
            Cipher        cipher   = Cipher.getInstance("AES/ECB/NoPadding");
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            return cipher.doFinal(data);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new byte[]{};
    }

    /**
     * AES解密
     *
     * @param data 将要解密的内容
     * @param key  密钥
     * @return 已经解密的内容
     */
    public static byte[] decrypt(byte[] data, byte[] key) {
        data = ArrayUtils.noPadding(data, -1);
        try {
            SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
            Cipher        cipher   = Cipher.getInstance("AES/ECB/NoPadding");
            cipher.init(Cipher.DECRYPT_MODE, skeySpec);
            byte[] decryptData = cipher.doFinal(data);
            int    len         = 2 + ByteUtils.byteToInt(decryptData[4]) + 3;
            return ArrayUtils.noPadding(decryptData, len);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new byte[]{};
    }

    public static String hexXorInvert(String hexStr) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < hexStr.length(); i++) {
            sb.append("f");
        }
        return xorWithInvert(hexStr, sb.toString());
    }

    private static String xorWithInvert(String hexString1, String hexString2) {
        // 将16进制字符串转换为字节数组
        byte[] bytes1 = new BigInteger(hexString1, 16).toByteArray();
        byte[] bytes2 = new BigInteger(hexString2, 16).toByteArray();

        // 对字节数组进行异或运算
        byte[] xorResult = xor(bytes1, bytes2);

        // 取反操作
        for (int i = 0; i < xorResult.length; i++) {
            xorResult[i] = (byte) ~xorResult[i];
        }

        // 将结果转换回16进制字符串
        return new BigInteger(1, xorResult).toString(16);
    }

    private static byte[] xor(byte[] bytes1, byte[] bytes2) {
        byte[] result = new byte[Math.max(bytes1.length, bytes2.length)];
        for (int i = 0; i < result.length; i++) {
            result[i] = (byte) (bytes1[i % bytes1.length] ^ bytes2[i % bytes2.length]);
        }
        return result;
    }
}